import React, {Component,Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Icon,
  Menu,
  Dropdown,
  Popover,
  InputNumber,
  DatePicker,
  message,
  Badge,
  Divider,
  Steps,
  Upload,
  Collapse, Empty,Table,
  Select,Button,Modal,Pagination
} from 'antd';
const Option = Select.Option;
const {MonthPicker, RangePicker} = DatePicker;
import CreateModal from './CreateModal/CreateModal'
import UpdateModal from './UpdateModal'
import FileModal from './FileModal'
@connect(({traffic, loading}) => ({
  traffic,
  loading: loading.models.traffic,
}))
@Form.create()
export default class Traffic extends Component {
  getTypeName = (old_name)=>{
    let newName = '';

    switch (old_name){
      case  'airplane':
        newName = "飞机";
        break;
      case  'train':
        newName = "火车";
        break;
      case  'car':
        newName = "汽车";
        break;
      case  'foreign':
        newName = "国外";
        break;
      case  'inside':
        newName = "国内";
        break;
    }
    return newName;
  }
  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'traffic/fetch',
      payload:{
        "page_num": 1,
        "page_size": 10
      },
    });
  }
  tableChange = (pagination, filters, sorter) => {
    const params = {
      page_num: pagination.current,
      page_size: pagination.pageSize,
    };
    this.searchList(params);
  }
  searchList = (pagination)=>{
    const { traffic: {
      pagination :{
        page_num,
        page_size
      }
    },dispatch} = this.props;
    const pageInfo = pagination?pagination:{page_num,page_size}
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const valuesEnd = {
          ...pageInfo,
          ...values
        };
        /*if (values.role_name) {
          valuesEnd.role_name = values.role_name;
        }
        if (values.create_time && values.create_time.length > 0) {
          valuesEnd.created_time_from = moment(values.create_time[0]).format('YYYY-MM-DD HH:mm:ss');
          valuesEnd.created_time_to = moment(values.create_time[1]).format('YYYY-MM-DD HH:mm:ss');
        }*/
        const action = {
          type: `traffic/searchList`,
          payload: valuesEnd,
        };
        dispatch(action);
      }
    });
  }
  saveState=(parms)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'traffic/save',
      payload: {
        ...parms
      },
    });
  }
  showModal =(modal_type,record)=>{
    const { traffic: {
    },dispatch} = this.props;
    switch (modal_type){
      case 'create' :
        dispatch({
          type: 'traffic/showCreateModal',
        });
        break;
      case 'update' :
        dispatch({
          type: 'traffic/showUpdateModal',
          payload :{
            traffic_id : record.traffic_id
          }
        });
        break;
      case  'update_file' :
        dispatch({
          type: 'traffic/showFileModal',
          payload :{
            traffic_id : record.traffic_id
          }
        });
        break;
    }
  }
  delete =(traffic_id)=>{
    const { traffic: {
    },dispatch} = this.props;
    const _this  = this;
    Modal.confirm({
      okText: "确定",
      cancelText: "取消",
      title: '确认删除吗',
      content: '您确定要删除这条数据吗？',
      onOk() {
        dispatch({
          type: 'traffic/deleteById',
          payload :{
            traffic_id:traffic_id
          }
        }).then((r)=>{
          console.log(r);
          if (r){
            message.success('操作成功');
            _this.searchList({'page_size': 10,'page_num': 1,})
            _this.saveState({createModalVisible:false})
          }
        });
      }
    })

  }
  deleteFile= (parms)=>{
    const { traffic: {
    },dispatch} = this.props;
    dispatch({
      type: 'traffic/delTrafficFile',
      payload : {
        ...parms
      }
    }).then((r)=>{
      if (r){
        this.showModal('update_file',{traffic_id:parms.traffic_id});
        message.success('操作成功');
      }
    });
  }
  updateFile = (parms,callback)=>{
    console.log(parms);
    const { traffic: {
    },dispatch} = this.props;
    dispatch({
      type: 'traffic/updateTrafficFile',
      payload : {
        ...parms
      }
    }).then((r)=>{
      if (r){
        if (callback){
          callback()
        }else {
          this.showModal('update_file',{traffic_id:parms.trafficId});
        }
        message.success('操作成功');
        //callback(true);
      }
    });

  }
  updateModalSubmit=(values)=>{
    const { traffic: {
    },dispatch} = this.props;
    dispatch({
      type: 'traffic/updateTraffic',
      payload :{
        ...values
      }
    }).then((r)=>{
      console.log(r);
      if (r){
        message.success('操作成功');
        this.searchList({'page_size': 10,'page_num': 1,})
        this.saveState({updateModalVisible:false})
      }
    });
  }
  createOnSubmit=(values,callback)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'traffic/createTraffic',
      payload :{
        ...values
      }
    }).then((r)=>{
      console.log(r);
      callback();
      if (r){
        message.success('操作成功');
        this.searchList({'page_size': 10,'page_num': 1,})
        this.saveState({createModalVisible:false})
      }
    });
  }




  handleMenuClick = ({key},data)=>{
    //console.log(key,data);
    switch (key){
      case 'update':
        this.showModal('update', data)
        break;
      case 'delete' :
        this.delete(data.traffic_id)
        break;
      case 'update_file' :
        this.showModal('update_file', data)
        break;
    }
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { traffic_type_list} =this.props.traffic
    return (
      <Form onSubmit={(e)=>{
        e.preventDefault();
        this.searchList({'page_size': 10,'page_num': 1,})
      }} layout="inline">
        <div
          style={{
            fontSize: '16px',
            marginBottom: '15px',
          }}
        >
          <div style={{ height: 60 }}>
            <Row align="middle">
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>交通名称 :
                </div>
                {getFieldDecorator('traffic_title')(<Input placeholder="请输入" style={{ width: '65%' }}/>)}
              </Col>
              <Col xl={12} lg={12} sm={24} align="left" style={{ marginTop: 13 }}>
                <div style={{
                  marginTop: '2px',
                  marginRight: '4px',
                  display: 'inline-block',
                }}>交通方式类型 :
                </div>
                {getFieldDecorator('traffic_type')(
                  <Select allowClear  placeholder="请选择"  style={{ width: '65%' }}>
                    {
                      traffic_type_list.map((item)=>{
                        return  (
                          <Option key={item.value} value={item.value}>
                            {item.name}
                          </Option>
                        )
                      })
                    }
                  </Select>
                )}
              </Col>
            </Row>
          </div>
          <Row gutter={30}>
            <Col md={18} sm={24} align="left" style={{ paddingLeft: 10 }}>
              <span>
                  <Button type="primary" onClick={()=>this.showModal('create')}>
                    新建
                  </Button>
                </span>
            </Col>
            <Col md={6} sm={24} align="right" style={{ paddingLeft: 10 }}>
               <span>
                  <Button type="primary" htmlType="submit">查询</Button>
                  <Button style={{ marginLeft: 8 }} onClick={()=>{this.props.form.resetFields()}}>重置</Button>
               </span>
            </Col>
          </Row>
        </div>
      </Form>
    )

  }
  render() {
    const { traffic: {
      list,
      pagination ,
      createModalVisible,
      city_list,
      traffic_type_list ,
      country_type_list,
      updateModalVisible,
      updateData,
      fileModalVisible,
      itemImgFile,
      contentImgFile,
      carouselImageFile,
      carouselVideoFile
    }}=this.props;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total) =>
        `共有 ${parseInt(total)} 条数据 当前第${pagination.page_num}页`,
      ...pagination,
    };

    const columns= [
      {
        title: '交通标题',
        dataIndex: 'traffic_title',
        align: 'center',
        render: (text, record) => {
          return (
            <a >{record.traffic_title}</a>
          );
        },
      },
     /* {
        title: '其他内容',
        dataIndex: 'other_content',
        align: 'center',
      },*/
      {
        title: '交通方式类型',
        dataIndex: 'traffic_type',
        align: 'center',
        render :(text)=>{
          return this.getTypeName(text)
        }
      },
      // {
      //   title: '所属区域类型',
      //   dataIndex: 'country_type',
      //   align: 'center',
      //   render :(text)=>{
      //     return this.getTypeName(text)
      //   }
      // },
      {
        title: '操作',
        fixed: 'right',
        width: 250,
        render: (text, record) => {
          const menu = (
            <Menu onClick={(key)=>this.handleMenuClick(key,record)}>
              <Menu.Item key="update">
                <Icon type="edit" />
                编辑基础信息
              </Menu.Item>
              <Menu.Item key="update_file">
                <Icon type="edit" />
                编辑图片信息
              </Menu.Item>
              <Menu.Item key="delete">
                <Icon type="delete" />
                删除
              </Menu.Item>
            </Menu>
          );
          return (
            <Dropdown overlay={menu}>
              <Button>
                操作<Icon type="down" />
              </Button>
            </Dropdown>
          )
        },
        align: 'center',
      },
    ];


    return (
      <PageHeaderWrapper>.
        <div
          style={{
            backgroundColor: '#FFFFFF',
            paddingLeft: '5%',
            paddingRight: '5%',
          }}
        >
          {this.renderSimpleForm()}
          {
            fileModalVisible?
              <FileModal
                fileModalVisible={fileModalVisible}
                clseModal = {()=>{this.saveState({fileModalVisible:false})}}
                updateData = {updateData}
                deleteFile={this.deleteFile}
                updateFile={this.updateFile}
                saveState={this.saveState}
                itemImgFile={itemImgFile}
                contentImgFile={contentImgFile}
                carouselImageFile={carouselImageFile}
                carouselVideoFile={carouselVideoFile}
              />
              :[]
          }
          {
            updateModalVisible ?
              <UpdateModal
                updateModalVisible={updateModalVisible}
                clseModal = {()=>{this.saveState({updateModalVisible:false})}}
                city_list={city_list}
                traffic_type_list={traffic_type_list}
                country_type_list={country_type_list}
                updateData = {updateData}
                updateModalSubmit={this.updateModalSubmit}
              />
              :[]
          }
          {
            createModalVisible ?
              <CreateModal
                createModalVisible = {createModalVisible}
                clseModal = {()=>{this.saveState({createModalVisible:false})}}
                city_list={city_list}
                createOnSubmit={this.createOnSubmit}
                country_type_list={country_type_list}
                traffic_type_list={traffic_type_list}
              />
              :[]
          }
          <Table
            dataSource={list}
            columns={columns}
            rowKey={record => record.traffic_id}
            onChange={this.tableChange}
            pagination={paginationProps}
          />

        </div>

      </PageHeaderWrapper>
    );
  }
}
